<template>
	<view class="cart-container">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="购物车"
			:show-back="false"
			background-color="#FFFFFF"
			title-color="#333333"
			:border="true"
		>
			<template #right>
				<text v-if="!isEditMode" class="edit-btn" @click="toggleEditMode">编辑</text>
				<text v-else class="done-btn" @click="toggleEditMode">完成</text>
			</template>
		</ob-navbar>
		
		<!-- 购物车类型切换 -->
		<view class="cart-tabs">
			<view 
				class="tab-item"
				:class="{ 'tab-active': currentTab === 'personal' }"
				@click="switchTab('personal')"
			>
				<text class="tab-text">个人购物车</text>
				<view v-if="personalCartCount > 0" class="tab-badge">
					<text class="badge-text">{{ personalCartCount }}</text>
				</view>
			</view>
			<view 
				class="tab-item"
				:class="{ 'tab-active': currentTab === 'ship' }"
				@click="switchTab('ship')"
			>
				<text class="tab-text">船舶购物车</text>
				<view v-if="shipCartCount > 0" class="tab-badge">
					<text class="badge-text">{{ shipCartCount }}</text>
				</view>
			</view>
		</view>
		
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 加载状态 -->
			<view v-if="isLoading" class="loading-state">
				<ob-loading :visible="true" text="加载中..." />
			</view>
			
			<!-- 空购物车 -->
			<view v-else-if="!isLoading && (!currentCartItems || currentCartItems.length === 0)" class="empty-cart" @click="goShopping">
				<ob-empty 
					:image="'/static/images/empty-cart.png'"
					title="购物车是空的"
					:description="currentTab === 'personal' ? '快去挑选心仪的商品吧' : '为船舶添加一些必需品吧'"
				>
					<template #action>
						<button class="go-shopping-btn" @click="goShopping">
							<text class="btn-text">去逛逛</text>
						</button>
					</template>
				</ob-empty>
			</view>
			
			<!-- 购物车商品列表 -->
			<view v-else class="cart-content">
				<view class="valid-section">
					<!-- 全选控件 -->
					<view class="select-all-section">
						<view class="select-all" @click="toggleSelectAll">
							<view class="checkbox" :class="{ 'checkbox-checked': isAllSelected }">
								<text v-if="isAllSelected" class="checkbox-icon">✓</text>
							</view>
							<text class="select-text">全选</text>
						</view>
						<text v-if="selectedItems.length > 0" class="selected-count">
							已选择{{ selectedItems.length }}件商品
						</text>
					</view>
					
					<!-- 商品列表 -->
					<view class="cart-list">
						<view v-for="item in validItems" :key="item.id" class="cart-item">
							<view class="item-checkbox" @click="toggleItemSelect(item.id)">
								<view class="checkbox" :class="{ 'checkbox-checked': isItemSelected(item.id) }">
									<text v-if="isItemSelected(item.id)" class="checkbox-icon">✓</text>
								</view>
							</view>
							
							<view class="item-content" @click.stop="goToProduct(item.productId)">
								<image class="product-image" :src="item.productImage || '/static/images/default-product.png'" mode="aspectFill" />
								<view class="product-info">
									<text class="product-name">{{ item.productName }}</text>
									<text v-if="item.specText" class="product-spec">{{ item.specText }}</text>
									<view class="price-row">
										<uni-text class="current-price">¥{{ (item.price * item.quantity).toFixed(2) }}</uni-text>
										<uni-text v-if="item.originalPrice && item.originalPrice > 0" class="original-price">
											¥{{ (item.originalPrice * item.quantity).toFixed(2) }}
										</uni-text>
									</view>
								</view>
							</view>
							
							<view class="item-actions">
								<!-- 数量控制 -->
								<view v-if="!isEditMode" class="quantity-controls">
									<button 
										class="quantity-btn decrease"
										:disabled="item.quantity <= 1"
										@click.stop="changeQuantity(item.id, item.quantity - 1)"
									>
										<text class="btn-text">-</text>
									</button>
									<text class="quantity-text">{{ item.quantity }}</text>
									<button 
										class="quantity-btn increase"
										:disabled="item.quantity >= item.stock"
										@click.stop="changeQuantity(item.id, item.quantity + 1)"
									>
										<text class="btn-text">+</text>
									</button>
								</view>
								
								<!-- 编辑模式操作 -->
								<view v-else class="edit-actions">
									<button class="remove-btn" @click.stop="deleteCartItems([item.id])">删除</button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部结算栏 -->
		<view v-if="currentCartItems.length > 0" class="bottom-bar" :style="{ paddingBottom: safeAreaInsetBottom + 'px' }">
			<view v-if="!isEditMode" class="settlement-bar">
				<view class="total-info">
					<uni-text class="total-label">合计：</uni-text>
					<uni-text class="total-price">¥{{ totalPrice }}</uni-text>
				</view>
				<uni-button 
					class="checkout-btn"
					:class="{ 'btn-disabled': selectedItems.length === 0 }"
					:disabled="selectedItems.length === 0"
					@click="goToCheckout"
				>
					<uni-text class="btn-text">结算({{ selectedItems.length }})</uni-text>
				</uni-button>
			</view>
			
			<view v-else class="edit-bar">
				<uni-button 
					class="batch-remove-btn"
					:class="{ 'btn-disabled': selectedItems.length === 0 }"
					:disabled="selectedItems.length === 0"
					@click="batchRemove"
				>
					<uni-text class="btn-text">删除选中({{ selectedItems.length }})</uni-text>
				</uni-button>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isOperating" text="操作中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { getPlatform } from '../../utils/common.js'
import { cartApi } from '../../api/cart.js'
import { productApi } from '../../api/product.js'
import store from '../../store'

// 全局状态
// 使用已经注入的store，不需要重新声明
// const store = inject('$store')

// 响应式数据
const currentTab = ref('personal')
const personalCartItems = ref([])
const shipCartItems = ref([])
const selectedPersonalItems = ref([])
const selectedShipItems = ref([])
const isEditMode = ref(false)
const isLoading = ref(false)
const isOperating = ref(false)

// 获取系统信息
const platform = getPlatform()
const safeAreaInsetBottom = platform.safeAreaInsetBottom || 0

// 计算属性
const currentCartItems = computed(() => {
	console.log('计算当前购物车商品:', {
		currentTab: currentTab.value,
		personalItems: personalCartItems.value.length,
		shipItems: shipCartItems.value.length
	})
	return currentTab.value === 'personal' ? personalCartItems.value : shipCartItems.value
})

const validItems = computed(() => {
	const items = currentCartItems.value.filter(item => !item.isInvalid)
	console.log('有效商品数量:', items.length)
	return items
})

const personalCartCount = computed(() => {
	return personalCartItems.value.filter(item => !item.isInvalid).length
})

const shipCartCount = computed(() => {
	return shipCartItems.value.filter(item => !item.isInvalid).length
})

// 当前选中的商品列表（根据当前标签页）
const selectedItems = computed(() => {
	return currentTab.value === 'personal' ? selectedPersonalItems.value : selectedShipItems.value
})

const isAllSelected = computed(() => {
	return validItems.value.length > 0 && selectedItems.value.length === validItems.value.length
})

const totalPrice = computed(() => {
	// 计算选中商品的总价（单价 × 数量）
	return validItems.value.reduce((total, item) => {
		if (selectedItems.value.includes(item.id)) {
			return total + (item.price * item.quantity)
		}
		return total
	}, 0).toFixed(2)
})

// 页面生命周期
onMounted(() => {
	// 只加载当前标签页的数据
	loadCurrentTabData()
})

onShow(() => {
	// 只加载当前标签页的数据
	loadCurrentTabData()
})

// 加载购物车数据
const loadCartData = async () => {
	try {
		isLoading.value = true
		// 清空选择状态
		selectedPersonalItems.value = []
		selectedShipItems.value = []
		console.log('开始加载购物车数据，已清空选择状态')
		
		// 检查登录状态
		const isLoggedIn = store.state.isLoggedIn
		console.log('登录状态:', isLoggedIn)
		
		if (!isLoggedIn) {
			console.log('用户未登录，清空购物车数据')
			personalCartItems.value = []
			shipCartItems.value = []
			isLoading.value = false
			return
		}
		
		const userId = store.state.userInfo?.id
		console.log('用户ID:', userId)
		
		if (!userId) {
			console.log('用户ID无效，清空购物车数据')
			personalCartItems.value = []
			shipCartItems.value = []
			isLoading.value = false
			return
		}
		
		// 加载个人购物车数据
		const personalParams = {
			userId: store.state.userInfo.id,
			cartType: 1 // 个人购物车
		}
		console.log('个人购物车参数:', personalParams)
		
		const personalResult = await productApi.getCartList(personalParams)
		console.log('个人购物车结果:', personalResult)
		
		// 兼容请求封装返回的“已解包数据”与原始Result结构
		const personalList = Array.isArray(personalResult)
			? personalResult
			: (Array.isArray(personalResult?.data) ? personalResult.data : [])
		
		if (Array.isArray(personalList) && personalList.length >= 0) {
			personalCartItems.value = personalList.map((item, index) => {
				console.log('原始商品数据:', item)
				// 使用后端返回的orderId作为itemId，这样删除时传递的就是正确的itemId
				const itemId = item.orderId || item.id || item.cartId || item.productId || item.itemId || index
				const mappedItem = {
					id: parseInt(itemId), // 确保ID是数字类型
					productId: item.productId,
					productName: item.productName,
					productImage: item.pic || item.productImage || '/static/images/default-product.png',
					specText: item.specText || `规格：${item.specValue || item.specName || '默认规格'}`,
					specId: item.specValueId, // 保留原始规格值ID用于下单
					price: parseFloat(item.totalPrice) || parseFloat(item.price) || 0,
					originalPrice: parseFloat(item.originalPrice) || 0,
					quantity: parseInt(item.quantity) || 1,
					stock: parseInt(item.stock) || 999,
					isInvalid: item.stock <= 0 || item.status === 0
				}
				console.log('个人购物车商品映射:', { 原始数据: item, 使用的orderId: item.orderId, 使用的ID: itemId, 映射后ID: mappedItem.id, 类型: typeof mappedItem.id })
				return mappedItem
			})
			console.log('个人购物车映射后数据:', personalCartItems.value)
		} else {
			console.log('个人购物车数据为空或格式错误')
			personalCartItems.value = []
		}
		
		// 加载船舶购物车数据
		const shipParams = {
			userId: store.state.userInfo.id,
			cartType: 2 // 船舶购物车
		}
		console.log('船舶购物车参数:', shipParams)
		
		const shipResult = await productApi.getCartList(shipParams)
		console.log('船舶购物车结果:', shipResult)
		
		// 同样兼容“已解包数据”与原始Result结构
		const shipList = Array.isArray(shipResult)
			? shipResult
			: (Array.isArray(shipResult?.data) ? shipResult.data : [])
		
		if (Array.isArray(shipList) && shipList.length >= 0) {
			shipCartItems.value = shipList.map((item, index) => {
				console.log('原始船舶商品数据:', item)
				// 使用后端返回的orderId作为itemId，这样删除时传递的就是正确的itemId
				const itemId = item.orderId || item.id || item.cartId || item.productId || item.itemId || (1000 + index)
				const mappedItem = {
					id: parseInt(itemId), // 确保ID是数字类型
					productId: item.productId,
					productName: item.productName,
					productImage: item.pic || item.productImage || '/static/images/default-product.png',
					specText: item.specText || `规格：${item.specValue || item.specName || '默认规格'}`,
					specId: item.specValueId, // 保留原始规格值ID用于下单
					price: parseFloat(item.totalPrice) || parseFloat(item.price) || 0,
					originalPrice: parseFloat(item.originalPrice) || 0,
					quantity: parseInt(item.quantity) || 1,
					stock: parseInt(item.stock) || 999,
					isInvalid: item.stock <= 0 || item.status === 0
				}
				console.log('船舶购物车商品映射:', { 原始数据: item, 使用的orderId: item.orderId, 使用的ID: itemId, 映射后ID: mappedItem.id, 类型: typeof mappedItem.id })
				return mappedItem
			})
			console.log('船舶购物车映射后数据:', shipCartItems.value)
		} else {
			console.log('船舶购物车数据为空或格式错误')
			shipCartItems.value = []
		}
		
		// 更新全局购物车数量
		const totalCount = personalCartCount.value + shipCartCount.value
		store.actions.setCartCount(totalCount)
		
		selectedItems.value = []
		
	} catch (error) {
		console.error('加载购物车数据失败:', error)
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
		// 出错时也要清空数据
		personalCartItems.value = []
		shipCartItems.value = []
	} finally {
		isLoading.value = false
		console.log('购物车加载完成，当前状态:', {
			isLoading: isLoading.value,
			personalCartItems: personalCartItems.value.length,
			shipCartItems: shipCartItems.value.length,
			currentTab: currentTab.value
		})
	}
}

// 加载当前标签页数据
const loadCurrentTabData = async () => {
	try {
		isLoading.value = true
		// 清空当前标签页的选择状态
		if (currentTab.value === 'personal') {
			selectedPersonalItems.value = []
		} else {
			selectedShipItems.value = []
		}
		
		console.log(`开始加载${currentTab.value === 'personal' ? '个人' : '船舶'}购物车数据`)
		
		// 检查登录状态
		const isLoggedIn = store.state.isLoggedIn
		console.log('登录状态:', isLoggedIn)
		
		if (!isLoggedIn) {
			console.log('用户未登录，清空购物车数据')
			personalCartItems.value = []
			shipCartItems.value = []
			isLoading.value = false
			return
		}
		
		const userId = store.state.userInfo?.id
		console.log('用户ID:', userId)
		
		if (!userId) {
			console.log('用户ID无效，清空购物车数据')
			personalCartItems.value = []
			shipCartItems.value = []
			isLoading.value = false
			return
		}
		
		// 根据当前标签页加载对应数据
		if (currentTab.value === 'personal') {
			await loadPersonalCartData(userId)
		} else {
			await loadShipCartData(userId)
		}
		
		// 更新全局购物车数量
		const totalCount = personalCartCount.value + shipCartCount.value
		store.actions.setCartCount(totalCount)
		
	} catch (error) {
		console.error('加载购物车数据失败:', error)
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
		console.log(`${currentTab.value === 'personal' ? '个人' : '船舶'}购物车加载完成`)
	}
}

// 加载个人购物车数据
const loadPersonalCartData = async (userId) => {
	const personalParams = {
		userId: userId,
		cartType: 1 // 个人购物车
	}
	console.log('个人购物车参数:', personalParams)
	
	const personalResult = await productApi.getCartList(personalParams)
	console.log('个人购物车结果:', personalResult)
	
	// 兼容请求封装返回的"已解包数据"与原始Result结构
	const personalList = Array.isArray(personalResult)
		? personalResult
		: (Array.isArray(personalResult?.data) ? personalResult.data : [])
	
	if (Array.isArray(personalList) && personalList.length >= 0) {
		personalCartItems.value = personalList.map((item, index) => {
			console.log('原始商品数据:', item)
			// 使用后端返回的orderId作为itemId，这样删除时传递的就是正确的itemId
			const itemId = item.orderId || item.id || item.cartId || item.productId || item.itemId || index
			const mappedItem = {
				id: parseInt(itemId), // 确保ID是数字类型
				productId: item.productId,
				productName: item.productName,
				productImage: item.pic || item.productImage || '/static/images/default-product.png',
				specText: item.specText || `规格：${item.specValue || item.specName || '默认规格'}`,
				specId: item.specValueId, // 保留原始规格值ID用于下单
				price: parseFloat(item.totalPrice) || parseFloat(item.price) || 0,
				originalPrice: parseFloat(item.originalPrice) || 0,
				quantity: parseInt(item.quantity) || 1,
				stock: parseInt(item.stock) || 999,
				isInvalid: item.stock <= 0 || item.status === 0
			}
			console.log('个人购物车商品映射:', { 原始数据: item, 使用的orderId: item.orderId, 使用的ID: itemId, 映射后ID: mappedItem.id, 类型: typeof mappedItem.id })
			return mappedItem
		})
		console.log('个人购物车映射后数据:', personalCartItems.value)
	} else {
		console.log('个人购物车数据为空或格式错误')
		personalCartItems.value = []
	}
}

// 加载船舶购物车数据
const loadShipCartData = async (userId) => {
	const shipParams = {
		userId: userId,
		cartType: 2 // 船舶购物车
	}
	console.log('船舶购物车参数:', shipParams)
	
	const shipResult = await productApi.getCartList(shipParams)
	console.log('船舶购物车结果:', shipResult)
	
	// 同样兼容"已解包数据"与原始Result结构
	const shipList = Array.isArray(shipResult)
		? shipResult
		: (Array.isArray(shipResult?.data) ? shipResult.data : [])
	
	if (Array.isArray(shipList) && shipList.length >= 0) {
		shipCartItems.value = shipList.map((item, index) => {
			console.log('原始船舶商品数据:', item)
			// 使用后端返回的orderId作为itemId，这样删除时传递的就是正确的itemId
			const itemId = item.orderId || item.id || item.cartId || item.productId || item.itemId || (1000 + index)
			const mappedItem = {
				id: parseInt(itemId), // 确保ID是数字类型
				productId: item.productId,
				productName: item.productName,
				productImage: item.pic || item.productImage || '/static/images/default-product.png',
				specText: item.specText || `规格：${item.specValue || item.specName || '默认规格'}`,
				specId: item.specValueId, // 保留原始规格值ID用于下单
				price: parseFloat(item.totalPrice) || parseFloat(item.price) || 0,
				originalPrice: parseFloat(item.originalPrice) || 0,
				quantity: parseInt(item.quantity) || 1,
				stock: parseInt(item.stock) || 999,
				isInvalid: item.stock <= 0 || item.status === 0
			}
			console.log('船舶购物车商品映射:', { 原始数据: item, 使用的orderId: item.orderId, 使用的ID: itemId, 映射后ID: mappedItem.id, 类型: typeof mappedItem.id })
			return mappedItem
		})
		console.log('船舶购物车映射后数据:', shipCartItems.value)
	} else {
		console.log('船舶购物车数据为空或格式错误')
		shipCartItems.value = []
	}
}

// 切换购物车类型
const switchTab = (tab) => {
	if (currentTab.value !== tab) {
		currentTab.value = tab
		// 清空编辑模式
		isEditMode.value = false
		// 加载对应标签页的数据（如果还没有加载过）
		const targetItems = tab === 'personal' ? personalCartItems.value : shipCartItems.value
		if (targetItems.length === 0) {
			loadCurrentTabData()
		}
	}
}

// 切换编辑模式
const toggleEditMode = () => {
	isEditMode.value = !isEditMode.value
	if (!isEditMode.value) {
		// 清空当前标签页的选择状态
		if (currentTab.value === 'personal') {
			selectedPersonalItems.value = []
		} else {
			selectedShipItems.value = []
		}
	}
}

// 选择相关操作
const toggleSelectAll = () => {
	if (isAllSelected.value) {
		if (currentTab.value === 'personal') {
			selectedPersonalItems.value = []
		} else {
			selectedShipItems.value = []
		}
	} else {
		if (currentTab.value === 'personal') {
			selectedPersonalItems.value = validItems.value.map(item => parseInt(item.id))
		} else {
			selectedShipItems.value = validItems.value.map(item => parseInt(item.id))
		}
	}
	// 更新选中商品数量和总价
	calculateSelectedInfo()
}

const toggleItemSelect = (itemId) => {
	// 确保itemId是数字类型
	const numericItemId = parseInt(itemId)
	console.log('切换商品选择状态:', { 原始ID: itemId, 数字ID: numericItemId, 类型: typeof numericItemId, 当前标签页: currentTab.value })
	if (currentTab.value === 'personal') {
		const index = selectedPersonalItems.value.indexOf(numericItemId)
		if (index > -1) {
			selectedPersonalItems.value.splice(index, 1)
			console.log('取消选择商品:', numericItemId, '个人购物车选中:', selectedPersonalItems.value)
		} else {
			selectedPersonalItems.value.push(numericItemId)
			console.log('选择商品:', numericItemId, '个人购物车选中:', selectedPersonalItems.value)
		}
	} else {
		const index = selectedShipItems.value.indexOf(numericItemId)
		if (index > -1) {
			selectedShipItems.value.splice(index, 1)
			console.log('取消选择商品:', numericItemId, '船舶购物车选中:', selectedShipItems.value)
		} else {
			selectedShipItems.value.push(numericItemId)
			console.log('选择商品:', numericItemId, '船舶购物车选中:', selectedShipItems.value)
		}
	}
	// 更新选中商品数量和总价
	calculateSelectedInfo()
}

const isItemSelected = (itemId) => {
	const isSelected = selectedItems.value.includes(itemId)
	console.log('检查商品选择状态:', {
		itemId,
		currentTab: currentTab.value,
		selectedPersonalItems: selectedPersonalItems.value,
		selectedShipItems: selectedShipItems.value,
		selectedItems: selectedItems.value,
		isSelected
	})
	return isSelected
}

// 计算选中商品的数量和总价
const calculateSelectedInfo = () => {
	// 由于使用了计算属性，这里不需要额外计算，只需要触发视图更新
	// 如果需要在这里执行其他操作，可以添加相应的逻辑
}

// 数量操作
const changeQuantity = async (itemId, targetQuantity) => {
	const item = validItems.value.find(item => item.id === itemId)
	if (!item) return
	
	if (targetQuantity < 1 || targetQuantity > item.stock) return
	
	try {
		isOperating.value = true
		
		// 调用API更新购物车商品数量 - 直接传递目标数量
		const result = await productApi.updateCartItem({
			itemId: itemId,
			quantity: targetQuantity
		})
		
		if (result === true || result?.code === 200 || result?.success === true || result?.status === 'success') {
			// 更新本地数据
			item.quantity = targetQuantity
			
			// 更新全局购物车数量
			const totalCount = personalCartCount.value + shipCartCount.value
			store.actions.setCartCount(totalCount)
			
			uni.showToast({
				title: '数量更新成功',
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: result?.message || '更新失败，请重试',
				icon: 'none'
			})
		}
		
	} catch (error) {
		console.error('更新数量失败:', error)
		uni.showToast({
			title: '更新失败，请重试',
			icon: 'none'
		})
	} finally {
		isOperating.value = false
	}
}



// 批量删除
const batchRemove = () => {
	uni.showModal({
		title: '确认删除',
		content: `确定要删除选中的${selectedItems.value.length}件商品吗？`,
		success: async (res) => {
			if (res.confirm) {
				const currentSelectedItems = currentTab.value === 'personal' ? selectedPersonalItems : selectedShipItems
				// 调用统一的删除方法
				await deleteCartItems(currentSelectedItems.value)
				// 清空选中状态
				currentSelectedItems.value = []
			}
		}
	})
}

// 删除购物车商品（支持单个或多个）
const deleteCartItems = async (itemIds) => {
	try {
		isOperating.value = true
		
		// 确保itemIds是数字类型数组
		const numericItemIds = itemIds.map(id => parseInt(id))
		console.log('删除商品ID转换:', { 原始IDs: itemIds, 数字IDs: numericItemIds })
		
		// 调用API删除购物车商品
		const result = await productApi.deleteCartItems({
			itemIds: numericItemIds,
			userId: store.state.userInfo.id
		})
		
		if (result === true || result?.code === 200 || result?.success === true || result?.status === 'success') {
			// 更新本地数据
			const items = currentTab.value === 'personal' ? personalCartItems.value : shipCartItems.value
			itemIds.forEach(itemId => {
				const index = items.findIndex(item => item.id === itemId)
				if (index > -1) {
					items.splice(index, 1)
				}
			})
			
			// 移除选中状态
			const currentSelectedItems = currentTab.value === 'personal' ? selectedPersonalItems : selectedShipItems
			itemIds.forEach(itemId => {
				const selectedIndex = currentSelectedItems.value.indexOf(itemId)
				if (selectedIndex > -1) {
					currentSelectedItems.value.splice(selectedIndex, 1)
				}
			})
			
			// 更新全局购物车数量
			const totalCount = personalCartCount.value + shipCartCount.value
			store.actions.setCartCount(totalCount)
			
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: result?.message || '删除失败，请重试',
				icon: 'none'
			})
		}
		
	} catch (error) {
		console.error('删除商品失败:', error)
		uni.showToast({
			title: '删除失败，请重试',
			icon: 'none'
		})
	} finally {
		isOperating.value = false
	}
}

// 页面跳转
const goShopping = () => {
	// 跳转到分类页面
	uni.switchTab({
		url: '/pages/category/index'
	})
}



const goToProduct = (productId, event) => {
	// 阻止事件冒泡，防止触发商品选择
	if (event) {
		event.stopPropagation()
	}
	uni.navigateTo({
		url: `/pages/product/detail?id=${productId}`
	})
}

const goToCheckout = () => {
	if (selectedItems.value.length === 0) {
		uni.showToast({
			title: '请选择要结算的商品',
			icon: 'none'
		})
		return
	}
	
	// 获取选中的商品信息
	const orderData = {
		items: selectedItems.value.map(itemId => {
			const item = validItems.value.find(item => item.id === itemId)
			return {
				cartItemId: itemId,
				productId: item.productId,
				specId: item.specId,
				specValueId: item.specId, // 后端期望的字段名
				quantity: item.quantity,
				price: item.price,
				// 展示用字段，供确认页直接渲染
				productName: item.productName,
				productImage: item.productImage,
				selectedSpec: item.specText
			}
		}),
		type: 'cart',
		cartType: currentTab.value
	}
	
	// 将选中商品信息存储到本地，以便结算页面使用
	uni.setStorageSync('checkoutItems', JSON.stringify(orderData.items))
	uni.setStorageSync('checkoutType', currentTab.value)
	
	uni.navigateTo({
		url: `/pages/order/confirm?data=${encodeURIComponent(JSON.stringify(orderData))}`
	})
}
</script>

<style lang="scss" scoped>
.cart-container {
	min-height: 100vh;
	background: #FFFFFF;
}

.edit-btn,
.done-btn {
	font-size: 16px;
	color: var(--primary-color);
	padding: 5px 10px;
}

.cart-tabs {
	background: #FFFFFF;
	display: flex;
}

.tab-item {
	flex: 1;
	height: 50px;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	
	&.tab-active {
		border-bottom: 2px solid var(--primary-color);
		
		.tab-text {
			color: var(--primary-color);
			font-weight: 600;
		}
	}
}

.tab-text {
	font-size: 16px;
	color: #666666;
}

.tab-badge {
	position: absolute;
	top: 8px;
	right: 20px;
	background: #ff4757;
	border-radius: 10px;
	min-width: 20px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.badge-text {
		font-size: 12px;
		color: #FFFFFF;
		font-weight: bold;
	}
}

.main-content {
	flex: 1;
	padding-bottom: 100px;
	padding-top: 0;
	margin-top: 0;
}

.loading-state {
	padding: 100px 0;
}

.empty-cart {
	padding: 100px 20px;
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 100%;
}

.go-shopping-btn {
	background: var(--primary-color);
	border: none;
	border-radius: 20px;
	padding: 8px 20px;
	margin-top: 20px;
	
	.btn-text {
		font-size: 14px;
		color: #FFFFFF;
		font-weight: 500;
	}
}

.cart-content {
	margin-top: 0;
	padding-top: 0;
}

.valid-section {
	background: #FFFFFF;
}

.select-all-section {
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: #FFFFFF;
}

.select-all {
	display: flex;
	align-items: center;
	gap: 10px;
}

.checkbox {
	width: 20px;
	height: 20px;
	border: 2px solid #ddd;
	border-radius: 4px;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
	
	&.checkbox-checked {
		background: var(--primary-color);
		border-color: var(--primary-color);
	}
}

.checkbox-icon {
	color: #FFFFFF;
	font-size: 14px;
	font-weight: bold;
}

.select-text {
	font-size: 16px;
	color: #333333;
}

.selected-count {
	font-size: 14px;
	color: #666666;
}

.cart-list {
	
}

.cart-item {
	padding: 15px 20px;
	border-bottom: 1px solid #F8F9FA;
	display: flex;
	align-items: flex-start;
	gap: 15px;
	
	&:last-child {
		border-bottom: none;
	}
}

.item-checkbox {
	margin-top: 5px;
}

.item-content {
	flex: 1;
	display: flex;
	gap: 12px;
}

.product-image {
	width: 80px;
	height: 80px;
	border-radius: 8px;
	flex-shrink: 0;
	object-fit: cover;
	border: 1px solid #F0F0F0;
	background: #F8F9FA;
}

.product-info {
	flex: 1;
}

.product-name {
	font-size: 16px;
	color: #333333;
	line-height: 1.4;
	margin-bottom: 4px;
	display: block;
}

.product-spec {
	font-size: 14px;
	color: #999999;
	margin-bottom: 8px;
	display: block;
}

.price-row {
	display: flex;
	align-items: baseline;
	gap: 8px;
}

.current-price {
	font-size: 18px;
	font-weight: 600;
	color: #ff4757;
}

.original-price {
	font-size: 14px;
	color: #999999;
	text-decoration: line-through;
	margin-left: 5px;
}

.item-actions {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 10px;
}

.quantity-controls {
	display: flex;
	align-items: center;
	border: 1px solid #E0E0E0;
	border-radius: 4px;
	overflow: hidden;
}

.quantity-btn {
	width: 30px;
	height: 30px;
	background: #F8F9FA;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:disabled {
		opacity: 0.5;
	}
	
	.btn-text {
		font-size: 16px;
		color: #333333;
		font-weight: bold;
	}
}

.quantity-text {
	font-size: 16px;
	color: #333333;
	padding: 0 12px;
	min-width: 40px;
	text-align: center;
}

.edit-actions {
	display: flex;
	gap: 8px;
}

.remove-btn {
	padding: 6px 12px;
	border-radius: 4px;
	border: none;
	font-size: 14px;
	background: #ff4757;
	color: #FFFFFF;
}

.bottom-bar {
	position: fixed;
	bottom: 50px;
	left: 0;
	right: 0;
	background: #FFFFFF;
	border-top: 1px solid #F0F0F0;
	padding: 12px 15px;
	z-index: 1000;
	box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.settlement-bar {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 15px;
}

.total-info {
	flex: 1;
}

.total-label {
	font-size: 16px;
	color: #333333;
}

.total-price {
	font-size: 18px;
	font-weight: bold;
	color: #ff4757;
}

.checkout-btn {
	background-color: rgba(0, 121, 254, 1) !important;
	border: none !important;
	border-radius: 25px !important;
	padding: 0 !important;
	width: 100px !important;
	height: 30px !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
	line-height: 30px !important;
	
	&.btn-disabled {
		background-color: #ddd !important;
		cursor: not-allowed;
	}
	
	.btn-text {
		font-size: 14px !important;
		color: #FFFFFF !important;
		font-weight: 500 !important;
		line-height: 1 !important;
	}
}

.edit-bar {
	display: flex;
	gap: 15px;
}

.batch-remove-btn {
	flex: 1 !important;
	height: 45px !important;
	border: none !important;
	border-radius: 22px !important;
	background: #ff4757 !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
	line-height: 45px !important;
	
	&.btn-disabled {
		background: #ddd !important;
		cursor: not-allowed;
	}
	
	.btn-text {
		font-size: 16px !important;
		color: #FFFFFF !important;
		font-weight: 600 !important;
		line-height: 1 !important;
	}
}
</style>